//
//  OrderViewController.m
//  LoverGo
//
//  Created by liudonghuan on 14-9-11.
//  Copyright (c) 2014年 yexiao. All rights reserved.
//

#import "OrderViewController.h"
#import "LGUtil.h"
#import "DataCenter.h"
#import "JoinSureViewController.h"
@interface OrderViewController ()

@end

@implementation OrderViewController
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//第一次进入初始化同时加载主题页面
-(id)init{
    self = [super init];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}
-(void)loadView
{
    
    [self dinglan];
    //初始化静态数据
    _pageNumTuiJian = 1;
    _pageNumHuoDong = 1;
    _whichTable = 0;
    _totalDataleft = [[NSMutableArray alloc]init];
    _totalDataright = [[NSMutableArray alloc]init];
    //根页面及代理
    _orderV = [[OrderView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _orderV.scrollView.delegate = self;
    _orderV.tableViewleft.delegate = self;
    _orderV.tableViewleft.dataSource = self;
    _orderV.tableViewright.delegate = self;
    _orderV.tableViewright.dataSource = self;
    _orderV.orderDelegate = self;
    _piao = [[PiaoView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _piao.piaoDelegate = self;
    _piao.backgroundColor = LGCOLOR_gray;
    
    //设置
    [self setupRefresh];
    [_orderV.tableViewleft headerBeginRefreshing];
    [self setView:_orderV];
}
-(void)dinglan{
    UIButton * backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0,20, 20)];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"btn_back.png"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(dinglanBackBtn) forControlEvents:UIControlEventTouchUpInside] ;
    [backBtn setShowsTouchWhenHighlighted:YES] ;
    UIBarButtonItem *backbutton = [[UIBarButtonItem alloc]initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = backbutton;
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(90, 0, 140, 30)];
    title.textAlignment = UITextAlignmentCenter;
    title.textColor = LGCOLOR_blue;
    title.text = @"我的订单";
    self.navigationItem.titleView = title;
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"barBG.png"] forBarMetrics:UIBarMetricsDefault];
}
-(void)dinglanBackBtn{
    [self.navigationController popViewControllerAnimated:YES];
}
//删除订单回来后刷新
-(void)viewWillAppear:(BOOL)animated
{    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"订单"];
    [_orderV.tableViewleft headerBeginRefreshing];
}
//主题活动2个按钮点击后切换界面的事件，0表示按的主题按钮，1表示按的活动按钮
-(void)ChangeViewWith:(OrderView *)view whichLabel:(whichLabel)which
{
    if (_whichTable == 0) {
        if (which == TuiJianBtn) {
            //当前页上面都不作
        }else if (which == HuoDongBtn){
            UIColor *color =[UIColor colorWithPatternImage:[UIImage imageNamed:@"firstview_blueline.png"]];
            [view.tjBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [view.hdBtn setTitleColor:LGCOLOR_blue forState:UIControlStateNormal];
            view.tjBtn.backgroundColor =  [UIColor whiteColor];
            view.hdBtn.backgroundColor =  color;
            _whichTable = 1;
            [_orderV.scrollView setContentOffset:CGPointMake(320, 0) animated:YES];
            if (_totalDataright.count == 0) {
                [_orderV.tableViewright headerBeginRefreshing];
            }
        }
    }else if (_whichTable == 1){
        if (which == HuoDongBtn) {
            //当前页面什么都不做
        }else if (which == TuiJianBtn){
            [view.hdBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [view.tjBtn setTitleColor:LGCOLOR_blue forState:UIControlStateNormal];
            view.hdBtn.backgroundColor =  [UIColor whiteColor];
            view.tjBtn.backgroundColor =  LGCOLOR_tjhd_btn;
            _whichTable = 0;
            [_orderV.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
            if (_totalDataleft.count == 0) {
                [_orderV.tableViewleft headerBeginRefreshing];
            }
        }
    }
    
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    float a = _orderV.scrollView.contentOffset.x;
    if (scrollView == _orderV.scrollView) {
        if (a == 320) {
            UIColor *color =[UIColor colorWithPatternImage:[UIImage imageNamed:@"firstview_blueline.png"]];
            [_orderV.tjBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [_orderV.hdBtn setTitleColor:LGCOLOR_blue forState:UIControlStateNormal];
            _orderV.tjBtn.backgroundColor =  [UIColor whiteColor];
            _orderV.hdBtn.backgroundColor =  color;
            _whichTable = 1;
            if (_totalDataright.count == 0) {
                [_orderV.tableViewright headerBeginRefreshing];
            }
        }else if (a == 0){
            [_orderV.hdBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [_orderV.tjBtn setTitleColor:LGCOLOR_blue forState:UIControlStateNormal];
            _orderV.hdBtn.backgroundColor =  [UIColor whiteColor];
            _orderV.tjBtn.backgroundColor =  LGCOLOR_tjhd_btn;
            _whichTable = 0;
            if (_totalDataleft.count == 0) {
                [_orderV.tableViewleft headerBeginRefreshing];
            }
        }
    }
    
}

#pragma mark - Table view data source and delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_whichTable == 0) {
        return _totalDataleft.count;
    }else{
        return _totalDataright.count;
    }
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(_whichTable == 0){
        //加标识重用机制
        NSString * orderTVIden = [NSString stringWithFormat:@"%@%ld",@"OrderTableViewCell",(long)[indexPath row]];
        OrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:orderTVIden];
        if (cell){
            return cell;
        }else{
            cell = [[OrderTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                             reuseIdentifier:orderTVIden];
        }
        NSMutableDictionary*  dict = _totalDataleft[indexPath.row];
        cell.orderTitle.text =[dict objectForKey:@"orderName"];
        cell.orderNum.text = [NSString stringWithFormat:@"%@%@",@"订单号：",[dict objectForKey:@"orderNo"]];
        cell.orderTime.text = [NSString stringWithFormat:@"%@%@",@"下单时间：",[dict objectForKey:@"insertTime"]];
        cell.orderPrice.text = [NSString stringWithFormat:@"%@%@",@"总价：",[dict objectForKey:@"totalPrice"]];
        return cell;
    }else{
        NSString * huoDongViewCell = [NSString stringWithFormat:@"%@%ld",@"OrderTableViewCell",(long)[indexPath row]];
        OrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:huoDongViewCell];
        if (cell){
            return cell;
        }else{
            cell = [[OrderTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                             reuseIdentifier:huoDongViewCell];
            NSMutableDictionary*  dict = _totalDataright[indexPath.row];
            cell.orderTitle.text =[dict objectForKey:@"orderName"];
            cell.orderNum.text = [NSString stringWithFormat:@"%@%@",@"订单号：",[dict objectForKey:@"orderNo"]];
            cell.orderTime.text = [NSString stringWithFormat:@"%@%@",@"下单时间：",[dict objectForKey:@"insertTime"]];
            cell.orderPrice.text = [NSString stringWithFormat:@"%@%@",@"总价：",[dict objectForKey:@"totalPrice"]];
        }
        return cell;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _orderV.tableViewleft) {
        NSMutableDictionary*  dict = _totalDataleft[indexPath.row];
        JoinSureViewController *_joinSureV = [[JoinSureViewController alloc]initWithDic:dict Time:[dict objectForKey:@"insertTime"] PayType:fromUnPay];
        self.navigationItem.backBarButtonItem = [LGUtil getBackButton];
        [self.navigationController pushViewController:_joinSureV animated:YES];
        
    }else if(tableView == _orderV.tableViewright){
        
        NSMutableDictionary*  dict = _totalDataright[indexPath.row];
        _activiyUuid = [dict objectForKey:@"uuid"];
        _piao.title.text = [dict objectForKey:@"orderName"];
        _piao.dingdanhao.text = [dict objectForKey:@"orderNo"];
        _piao.taocanming.text = [dict objectForKey:@"orderName"];
        _piao.shuliang.text = [NSString stringWithFormat:@"%d",[[dict objectForKey:@"totalNum"]intValue]];
        _piao.jiage.text = [NSString stringWithFormat:@"%f",[[dict objectForKey:@"totalPrice"] floatValue]] ;
        _piao.xiadanshijian.text = [dict objectForKey:@"insertTime"];
        [self.view addSubview:_piao];
        _piao.shiyongqixian.text = [dict objectForKey:@"endTime"];
        
        
        //        JoinSureViewController *_joinSureV = [[JoinSureViewController alloc]initWithDic:dict Time:[dict objectForKey:@"activityTime"] PayType:fromHadPay];
        //        self.navigationItem.backBarButtonItem = [LGUtil getBackButton];
        //        [self.navigationController pushViewController:_joinSureV animated:YES];
    }
    
    
}
-(void)guanbipiao
{
    [_piao removeFromSuperview];
}
-(void)shanchupiao
{
    UIAlertView *alertfirst = [[UIAlertView alloc]initWithTitle:@"删除订单？" message:@"如果删除票劵将消失，可联系管理员恢复" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"删除", nil] ;
    [alertfirst show];
}
//处理弹出框事件
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        NSDictionary *para = [NSDictionary dictionaryWithObjectsAndKeys:
                              _activiyUuid,@"activityOrderUuid",
                              nil];
        [SVHTTPRequest POST:@"http://server.lover-go.com/activityOrder/deleteActivityOrder"
                 parameters:para
                 completion:^(id response, NSHTTPURLResponse *urlResponse, NSError *error) {
                     if (error) {
                         [[[[UIApplication sharedApplication] delegate] window] makeToast:@"网络接连失败"
                                                                                 duration:1.0
                                                                                 position:@"center"];
                         return ;
                     }
                     NSError *jsonError = nil;
                     id jsonObject = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:&jsonError];
                     if (jsonError) {
                         [[[[UIApplication sharedApplication] delegate] window] makeToast:@"数据解析异常"
                                                                                 duration:1.0
                                                                                 position:@"center"];
                     }else{
                         if ([[jsonObject objectForKey:@"status"] intValue] == 0) {
                             [[[[UIApplication sharedApplication] delegate] window] makeToast:@"删除订单成功"
                                                                                     duration:1.0
                                                                                     position:@"center"];
                         }
                         
                     }
                     
                 }];
        
    }
    [_orderV.tableViewright headerBeginRefreshing];
    [_piao removeFromSuperview];
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 60;
}

/**
 *  集成刷新控件
 */
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [_orderV.tableViewleft addHeaderWithTarget:self action:@selector(headerRereshing)];
    // [_contentView.myTableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [_orderV.tableViewleft addFooterWithTarget:self action:@selector(footerRereshing)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    _orderV.tableViewleft.headerPullToRefreshText = @"下拉可以刷新了";
    _orderV.tableViewleft.headerReleaseToRefreshText = @"松开加载未付款订单";
    _orderV.tableViewleft.headerRefreshingText = @"何不带上朋友大吃一顿？";
    
    _orderV.tableViewleft.footerPullToRefreshText = @"上拉加载数据";
    _orderV.tableViewleft.footerReleaseToRefreshText = @"松开加载已付款订单";
    _orderV.tableViewleft.footerRefreshingText = @"何不带上朋友大吃一顿？";
    
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [_orderV.tableViewright addHeaderWithTarget:self action:@selector(headerRereshing)];
    // [_contentView.myTableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [_orderV.tableViewright addFooterWithTarget:self action:@selector(footerRereshing)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    _orderV.tableViewright.headerPullToRefreshText = @"下拉可以刷新了";
    _orderV.tableViewright.headerReleaseToRefreshText = @"松开马上知道去哪儿";
    _orderV.tableViewright.headerRefreshingText = @"今天情侣去哪儿呢?";
    
    _orderV.tableViewright.footerPullToRefreshText = @"上拉加载数据";
    _orderV.tableViewright.footerReleaseToRefreshText = @"松开马上知道去哪儿";
    _orderV.tableViewright.footerRefreshingText = @"今天情侣去哪儿呢?";
}
#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (_whichTable == 0) {
            _pageNumTuiJian = 1;
            [self startRequest:[NSString stringWithFormat:@"%d",_pageNumTuiJian] Flag:0];
        }else if(_whichTable == 1){
            _pageNumHuoDong = 1;
            [self startRequest:[NSString stringWithFormat:@"%d",_pageNumHuoDong] Flag:0];
        }
        
    });
    
}

- (void)footerRereshing
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (_whichTable == 0) {
            _pageNumTuiJian = _pageNumTuiJian+1;
            [self startRequest:[NSString stringWithFormat:@"%d",_pageNumTuiJian] Flag:1];
        }else if (_whichTable == 1){
            _pageNumHuoDong = _pageNumHuoDong+1;
            [self startRequest:[NSString stringWithFormat:@"%d",_pageNumHuoDong] Flag:1];
        }
    });
}
/*
 * 开始请求Web Service
 */
-(void)startRequest:(NSString *)page Flag:(int)flag
{
    NSString *uuid;
    if ([DataCenter getSingleton].userInfo!=nil) {
        uuid = [[DataCenter getSingleton].userInfo uuid];
        if (_whichTable == 0 ) {
            NSDictionary *para = [NSDictionary dictionaryWithObjectsAndKeys:
                                  uuid,@"appUserUuid",
                                  @"pay0",@"payStatus",
                                  page,@"page",
                                  nil];
            [[RequestManager getSingleton] sendRequest:findActivityOrder para:para callBack:^(id responseObj) {
                [self loadData:responseObj Flag:flag];
            }];
        }
        else{
            UserInfo *userinfo = [[DataCenter getSingleton] userInfo];
            NSString *uuid = [userinfo uuid];
            NSDictionary *para = [NSDictionary dictionaryWithObjectsAndKeys:
                                  uuid,@"appUserUuid",
                                  @"pay2",@"payStatus",
                                  page,@"page",
                                  nil];
            [[RequestManager getSingleton] sendRequest:findActivityOrder para:para callBack:^(id responseObj) {
                [self loadData:responseObj Flag:flag];
                
            }];
        }
        
    }
    [_orderV.tableViewleft  footerEndRefreshing];
    [_orderV.tableViewleft  headerEndRefreshing];
    [_orderV.tableViewright headerEndRefreshing];
    [_orderV.tableViewright footerEndRefreshing];
}

-(void)loadData:(NSDictionary*)res Flag:(int)flag
{
    if (_whichTable == 0) {
        if (flag == 0) {//头部刷新
            [_totalDataleft removeAllObjects];
            _listDataleft =[res objectForKey:@"data"];
            [_totalDataleft addObjectsFromArray:_listDataleft];
            [_orderV.tableViewleft reloadData];
        }else{
            if(_listDataleft.count == 0) {
                _pageNumTuiJian = _pageNumTuiJian-1;
            }else{
                _listDataleft =[res objectForKey:@"data"];
                [_totalDataleft addObjectsFromArray:_listDataleft];
                [_orderV.tableViewleft reloadData];
            }
        }
    }else if (_whichTable == 1){
        if (flag == 0) {//头部刷新
            [_totalDataright removeAllObjects];
            _listDataright =[res objectForKey:@"data"];
            [_totalDataright addObjectsFromArray:_listDataright];
            [_orderV.tableViewright reloadData];
        }else{
            if(_listDataleft.count == 0) {
                _pageNumHuoDong = _pageNumHuoDong-1;
            }else{
                _listDataright =[res objectForKey:@"data"];
                [_totalDataright addObjectsFromArray:_listDataright];
                [_orderV.tableViewright reloadData];
            }
        }
    }
    
    
    
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"订单"];
}



@end
